// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require("axios")
const cheerio = require("cheerio")
cloud.init()
const db = cloud.database()

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  await axios({
    url: 'https://ak.hypergryph.com/index',
    method: 'get'
  }).then(res => {
    const $ = cheerio.load(res.data)
    const factionList = []
    $('div.factions ul.factions-list  li.factions-item').each((i, item) => {
      const characters = []
      $(`div.characters-wrapper div.characters-container`).eq(i).find('ul.characters-list li.characters-item').each((charaI, charaItem) => {
        const character = {
          cName: $(charaItem).find('.character-pc-name-c').text(),
          eName: $(charaItem).find('.character-pc-name-e').text(),
          intro: $(charaItem).find('.character-pc-description').text(),
          img: 'https://ak.hypergryph.com' + $(charaItem).find('img.character-pc-image').attr('src'),
          cv: $(charaItem).find('.character-pc-cv').text(),
          type: parseInt($(charaItem).find('.character-pc-type').attr('class').split('-').slice(-1).join('')),
          typeText: $(charaItem).find('.character-pc-type').text()
        }
        characters.push(character)
      })
      const obj = {
        title: $(item).find('a').attr('title'),
        img: `https://ak.hypergryph.com/assets/index/images/ak/pc/faction/${i + 1}-on.png`,
        icon: `https://ak.hypergryph.com/assets/index/images/ak/pc/faction/${i + 1}.png`,
        characters
      }
      factionList.push(obj)
    })

    const storyList = []
    $('div.story div.story-container li.story-item').each((i, item) => {
      const obj = {
        cHint: $(item).find('.story-hint-c').text(),
        eHint: $(item).find('.story-hint-e').text(),
        desc: $(item).find('.story-description').text(),
        img: 'https://ak.hypergryph.com' + $(item).find('.story-image-wrapper img').attr('src')
      }
      storyList.push(obj)
    })

    const archiveList = []
    $('div.archive div.archive-inner div.archive-item').each((i, item) => {
      const obj = {
        img: $(item).find('img').attr("src"),
        intro: $(item).find('img').attr("alt"),
      }
      archiveList.push(obj)
    })

    const result = {
      factionList,
      storyList,
      archiveList,
    }

    db.collection("arknights").add({
      data: result,
      createTime: db.serverDate()
    })
  })
}